#!/cygdrive/c/Perl/bin/perl
#
use GraphViz;
use Data::Dumper;

# expecting a file in form of:
# router, net, mask, nexthop
sub read_routes() {
	my ( @r, $l);
	while ($l=<STDIN>) {
		chomp $l;
		push @r, [split(",",$l)];
	}
	# print Dumper(@r);
	return @r;
}


sub create_tree(@) {
	my @routes = ( @_ ) ;
	my $nodes = ();
	my ( $r );

	# print Dumper(@routes);
	
	foreach $r (@routes) {
		$nodes->{$r->[0]}++;
		$nodes->{alias($r->[3])}++;
		print "Routes: $r->[0] - $r->[3]\n";
	}
	
	my $g = GraphViz->new(layout => 'twopi', ratio => 'auto', ranksep => '10' );
	
	foreach $n (keys(%{$nodes})) {
		$g->add_node($n);
	}
	
	foreach $r (@routes) {
		$g->add_edge($r->[0] => alias($r->[3]), label => sprintf "%s/%s",$r->[1],$r->[2]);
	}

	$g->as_png("pretty.png");
}


# maps nexthop's interfaces to device name
sub alias($) {
	my $ip = ( $_ );
	my ( $alias );
	
	$alias = (
		1.1.0.1	=> "r1",
		2.1.0.1	=> "r2",
		3.1.0.1	=> "r3",
		4.1.0.1	=> "r4",
		5.1.0.2	=> "r5",
		5.2.0.2	=> "r5",
		5.3.0.2	=> "r5",
		5.4.0.2	=> "r5",
	);
	
	if ( $alias->{$ip} ) {
		# printf "Found        ip: %s - alias: %s\n", $ip, $alias->{$ip};
		return $alias->{$ip};
	} else {
		# printf "NOT Found -- ip: %s - alias: %s\n", $ip, $ip;
		return $ip;
	}
	
}


#
# Main
#
print "Starting ...\n";

my @routes = read_routes;
create_tree(@routes);

print "End!\n";